package com.luck.emp.kind.logic;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;

import com.luck.emp.entity.EmpTProdKind;
import com.luck.pf.common.entity.UserBean;
import com.luck.pf.framework.dao.BaseJdbcDao;
import com.luck.pf.framework.logic.BaseLogic;
import com.luck.pf.util.CriteriaUtil;

/**
 * 说明
 * Copyright: Copyright (c) 2011
 * 深圳**科技
 * @author 
 * 
 */
public class KindLogic extends BaseLogic implements IKindLogic{
	private BaseJdbcDao jdbcDao;
	

	public List findProdKinds(UserBean userBean, Long orgId) throws Exception{
		Criteria criteria = this.baseDao.createCriteria(EmpTProdKind.class);
		//criteria.add(Restrictions.eq("deptId", userBean.getOrgId()));
		criteria.addOrder(Order.asc("id"));
		if(orgId != null)
			CriteriaUtil.addEq(criteria, "deptId", orgId);
		else{
			criteria.createAlias("dept", "d");
			filterData(criteria, userBean, "d", null);
		}
		return criteria.list();
	}
	/**
	 * 保存
	 **/
	public String saveKind(UserBean userBean, EmpTProdKind entity)   throws Exception{
		if(entity.getId() == null){
			entity.setTreeNo(generatorTreeNo(entity.getParentId()));
			entity.setDeptId(userBean.getOrgId());
		}
		super.save(entity);
		return null;
	}

	private String generatorTreeNo(Long parentId){
		EmpTProdKind kind = super.baseDao.get(EmpTProdKind.class, parentId);
		List list = baseDao.find(" SELECT max(treeNo) FROM EmpTProdKind WHERE parentId=? and deptId=?",new Object[]{parentId,kind.getDeptId()});
		if(list == null ||list.isEmpty()){
			return kind.getTreeNo()+"001";
		}else{
			String treeno = (String) list.get(0);
			if(StringUtils.isBlank(treeno))
				return kind.getTreeNo()+"001";
			else{
				Long no = new Long(treeno);
				return (no+1)+"";
			}
		}
	}
	/**
	 * 删除
	 */
	public String deleteKind(UserBean userBean, EmpTProdKind entity) throws Exception{
		StringBuffer bf = new StringBuffer();
		if(entity.getParentId() == null)
			bf.append("<br>此为根目录");
		int suns = super.baseDao.count(" select count(*) from EmpTProdKind WHERE parentId=?",entity.getId());
		if(suns>0)
			bf.append("<br>此机构下有分类");
		if(entity.getDeptId() != userBean.getDeptId())
			bf.append("<br>此分类属于其它机构");
		if(StringUtils.isBlank(bf.toString()))
			super.delete(entity);
		else
			throw new Exception(bf.toString());
		return bf.toString();
	}
	
	public BaseJdbcDao getJdbcDao() {
		return jdbcDao;
	}

	public void setJdbcDao(BaseJdbcDao jdbcDao) {
		this.jdbcDao = jdbcDao;
	}

}